package com.zjoin.stduy.volatiles;

import java.util.concurrent.TimeUnit;

/**
 * <p>深入理解volatile关键字<p/>
 *
 * @Author: 地瓜（yangxw）
 * @Date: 2020/4/8 12:55 AM
 */
public class VolatileTest {
    final static int MXA = 5;
    volatile static int init_value = 0;

    public static void main(String[] args) {
        new Thread(() -> {
            int local_value = init_value;
            while (local_value < MXA) {
//                System.out.printf("local_value=[%d],init_value=[%d]\n", local_value, init_value);
                if (init_value != local_value) {
                    System.out.printf("init_value 更新为[%d]\n", init_value);
                    local_value = init_value;
                }
            }
        }, "reader").start();

        new Thread(() -> {
            int local_value = init_value;
            while (local_value < MXA) {
                ++local_value;
                System.out.printf("init_value 变为[%d]\n", local_value);
                init_value = local_value;
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "update").start();
    }
}
